import json

import redis
from flask import Blueprint,request,jsonify
from flaskDemo.token.token_deal import generator_token,verify_token
from flaskDemo.sql.mysql_db import mysql_db
from flaskDemo.extensions.error import CustomExcetion
from flaskDemo.config.config import Config
from flaskDemo.extensions.success import map_result,list_result
from flaskDemo.config.encrypt import encrype,decrype
from flaskDemo.sql.sqlModel import SqlModel
# import redis
#使用user空间
user = Blueprint('user',__name__)
err = Config.ERR

@user.route("/login", methods=['GET','POST'])
def login():
    data = request.args
    userName = data.get("userName")
    pwd = data.get("pwd")
    pwd = encrype(pwd)
    sql = "select * from system_user where user_name = %s"
    with mysql_db() as db:
        data = db.fetch_one(sql, userName)
        if data is None:
            raise CustomExcetion(err["1001"][0], err["1001"][1])
        else:
            pwdOld = data["pwd"]
            pwdOld = decrype(pwdOld)
            if pwd == pwdOld:
                token = generator_token(data)
                del data["pwd"]
                sql = f"select GROUP_CONCAT(role_id) as role_id from system_user_role GROUP BY user_id HAVING user_id = '{data['id']}'"
                roleResult = db.fetch_one(sql)
                data["roleIds"] = roleResult['role_id']
                print(data["id"])
                redis.Redis().set("userId", data["id"])
                return map_result({"token": token, "data": data})
            else:
                raise CustomExcetion(err["1002"][0], err["1002"][1])

@user.route("/logout", methods=['GET','POST'])
def logout():
    print("登出")
#     可以将token 存在redis，退出的时候可以判断是否存在 如果存在就清空


@user.route("/getList")
def getList():
    params = request.values
    user_name = params.get("user_name")
    sql = f"select  a.user_name,a.login_name,a.pwd,a.avatar,a.motto,a.introduction,a.mobile,date_format(a.born_date,'%%Y-%%m-%%d') as born_date,a.sex,a.age,(select depart_name from system_depart where id = a.office_id) as  depart_name,a.office_id from system_user a where a.is_delete = 0"
    if user_name is not None:
        sql += f" and a.user_name like concat('%%','{user_name}','%%')"
    with mysql_db() as db:
        result = db.fetch_all(sql)
        return list_result(result)

@user.route("/getUserDetail")
def get_user_detail():
    return '用户列表'


@user.route("/addOrUpdUser")
def addOrUpdUser():
    params = request.json
    id = params.get("id")
    with mysql_db() as db:
        if id is not None:
            model = SqlModel("system_user", [params])
            sql = model.update_sql()
            sql = f"{sql} where id = '{id}'"
            db.update(sql)
            db.conn.commit()
            return list_result()
        else:
            model = SqlModel("system_user", [params])
            sql = model.insert_sql()
            db.insert(sql)
            db.conn.commit()
            return list_result()



